<template>
  <div class="common-table-container">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" inline class="common-search-form">
      <el-form-item label="角色名称">
        <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
        >
          <el-option label="启用" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="common-table-header">
      <div>
        <el-button type="primary" @click="handleAdd">新增角色</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="fixed-table-container">
      <el-table
          :data="tableData"
          class="common-table"
          v-loading="loading"
          stripe
          border
          height="100%"
      >
        <el-table-column prop="roleId" label="角色ID" width="80" align="center"/>
        <el-table-column prop="roleName" label="角色名称" min-width="120"/>
        <el-table-column prop="roleKey" label="角色编码" min-width="120"/>
        <el-table-column prop="roleSort" label="排序" width="80" align="center"/>
        <el-table-column prop="dataScope" label="数据范围" width="120" align="center">
          <template #default="scope">
            {{ getDataScopeText(scope.row.dataScope) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.status === '0' ? 'success' : 'danger'"
                class="status-tag"
            >
              {{ scope.row.status === '0' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"/>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(scope.row)"
              >编辑
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="common-pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框（暂时注释掉） -->
    <RoleDialog
        v-model="dialogVisible"
        :role-data="currentRole"
        :mode="dialogMode"
        @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {findRole, deleteRole} from '@/api/role'

import RoleDialog from './components/RoleDialog.vue'

const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRole = ref(null)

const searchForm = reactive({
  roleName: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const buildRequestParams = () => {
  return {
    ...searchForm,
    page: pagination.current,
    rows: pagination.size
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = buildRequestParams()
    const response = await findRole(params)

    if (response && response.data) {
      tableData.value = response.data.list || response.data
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

const getDataScopeText = (scope) => {
  const scopeMap = {
    '1': '全部数据',
    '2': '自定义数据',
    '3': '本部门数据',
    '4': '本部门及以下数据'
  }
  return scopeMap[scope] || scope
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.roleName = ''
  searchForm.status = ''
  pagination.current = 1
  fetchData()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchData()
}

const handleAdd = () => {
  dialogMode.value = 'add'
  currentRole.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  currentRole.value = {...row}
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除${row.roleName || row.deptName}吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        // 添加 catch 回调来处理取消操作
        callback: (action) => {
          if (action === 'cancel') {
            // 用户点击取消，不做任何操作
            return
          }
        }
      }
  ).then(async () => {
    try {
      if (row.roleId) {
        await deleteRole({roleId: row.roleId})
      } else if (row.deptId) {
        await deleteDept({deptId: row.deptId})
      }
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 这里捕获取消操作的错误，但不做任何处理
  })
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  fetchData()
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.common-table-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.common-table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.common-search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.common-table {
  width: 100%;
  margin-bottom: 20px;
}

.common-pagination {
  text-align: right;
  margin-top: auto;
}

.fixed-table-container {
  flex: 1;
  overflow: auto;
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.status-tag {
  margin-right: 5px;
}
</style>
